﻿#include "tcpresponder.h"
#include "widgettcpcfg.h"
#include "WaitUtils.h"

TcpResponder::TcpResponder(QObject *parent):BaseResponder(parent)
{
    _tcpServer=new QTcpServer(this);
    connect(_tcpServer,&QTcpServer::newConnection,this,&TcpResponder::onNewConnection);
    _mutex=new QMutex();
    _waitCondition=new QWaitCondition();
}

void TcpResponder::onNewConnection()
{
    // 获取与新客户端的连接
    QTcpSocket *clientSocket = _tcpServer->nextPendingConnection();
    QString clientKey = getKey(clientSocket);

     // 将客户端连接插入到 QMap 中
    _clients.insert(clientKey, clientSocket);
    qDebug() << "New client connected:" << clientKey;

    // 处理客户端发送的数据
    connect(clientSocket, &QTcpSocket::readyRead, this, &TcpResponder::onReadyRead);
    // 处理客户端断开连接
    connect(clientSocket, &QTcpSocket::disconnected, this, [this, clientKey]() {
         qDebug() << "Client disconnected:" << clientKey;
         _clients.remove(clientKey);
     });
}

QWidget *TcpResponder::getConfigWidget()
{
    WidgetTcpCfg *cfg=new WidgetTcpCfg();
    cfg->setComm(this);
    return cfg;
}

bool TcpResponder::connectToHost()
{
    QString hostAddr=getCommParam();
    const QUrl url = QUrl::fromUserInput(hostAddr);
    return _tcpServer->listen(QHostAddress::Any,url.port());
}

bool TcpResponder::isConnected()
{
    return _tcpServer->isListening();
}

bool TcpResponder::disConnect()
{
    _tcpServer->close();
    return true;
}

//void TcpResponder::response(QString clientKey, QByteArray data)
//{
//    if (_clients.contains(clientKey))
//    {
//        QTcpSocket *clientSocket = _clients.value(clientKey);
//        clientSocket->write(data);
//    }
//    else if(clientKey=="--"&&_clients.count()!=0)
//    {
//        _clients.first()->write(data);
//    }
//    else
//    {
//        qDebug() << "Client not found:" << clientKey;
//    }
//}

void TcpResponder::response(QByteArray data)
{
    QMutexLocker locker(_mutex);
    _sendQueue.enqueue(data);
}

void TcpResponder::onReadyRead()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QString clientKey=getKey(clientSocket);
    QByteArray data = clientSocket->readAll();
    emit onRequestWithKey(clientKey,data);
    emit onRequest(data);

    QElapsedTimer ela;
    ela.start();
    while(true)
    {
        WaitUtils::WaitMs(50);
        if(ela.elapsed()>3000)
        {
            clientSocket->write(QString("receive data ok but response timeout").toUtf8());
            break;
        }

        if(!_sendQueue.isEmpty())
        {
            clientSocket->write(_sendQueue.dequeue());
            break;
        }
    }
}

QString TcpResponder::getKey(QTcpSocket *socket)
{
    QHostAddress ipv4Address(socket->peerAddress().toIPv4Address());
    QString clientKey=QString("%1:%2")
            .arg(ipv4Address.toString())
            .arg(socket->peerPort());
    return clientKey;
}

